package com.etbsms.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import com.etbsms.dao.ICodeCountryDAO;
import com.etbsms.domain.CodeCountry;

@Repository
@Component("codeCountryDAO")
public class CodeCountryDAOImpl extends GenericDAOImpl<CodeCountry, String> 
	implements ICodeCountryDAO {


	@Override
	@SuppressWarnings("unchecked")
	public List<CodeCountry> getAll() {
		Session session = sessionFactory.openSession();
		Criteria criteria = session.createCriteria(CodeCountry.class);
		criteria.add(Restrictions.isNotNull("parent"));
		criteria.addOrder(Order.asc("parent"));
		List<CodeCountry> list = criteria.list();
		session.close();
		return list;
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<CodeCountry> query(String qr){
		qr = "%" + qr + "%";		
		
		Session session = sessionFactory.openSession();
		Criteria criteria = session.createCriteria(CodeCountry.class);
		criteria.add(Restrictions.isNotNull("parent"));
		
		Disjunction disj = Restrictions.disjunction();
		disj.add(Restrictions.ilike("code", qr));
		disj.add(Restrictions.ilike("name_en", qr));
		disj.add(Restrictions.ilike("name_ch", qr));
		criteria.add(disj);
						
		criteria.addOrder(Order.asc("parent"));
		List<CodeCountry> list = criteria.list();
		session.close();
		return list;
	}
	

}
